package middleware

import (
	"net/http"
	"time"

	"kubem/config"
	"kubem/pkg/logger"
	"kubem/pkg/response"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
)

// CustomClaims 自定义的Claims结构体，包含标准Claims以及自定义的用户相关信息
type CustomClaims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" {
			logger.Info("Missing Authorization header in request")
			c.JSON(http.StatusUnauthorized, response.Response{
				Code:    http.StatusUnauthorized,
				Message: "Missing Authorization header",
			})
			c.Abort()
			return
		}

		// 解析token，使用自定义的Claims结构体
		claims := &CustomClaims{}
		token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
			logger.Debug("secret: ", config.Conf.Jwt.Secret)
			return []byte(config.Conf.Jwt.Secret), nil
		})
		if err != nil {
			logger.Info("Invalid token in request")
			c.JSON(http.StatusUnauthorized, response.Response{
				Code:    http.StatusUnauthorized,
				Message: "Invalid token",
				Data:    nil,
			})
			c.Abort()
			return
		}

		// 判断token是否有效且未过期
		if token.Valid {
			// 检查是否存在过期时间的声明（exp），并进行验证
			if claims.ExpiresAt.Unix() < time.Now().Unix() {
				logger.Info("Token has expired")
				c.JSON(http.StatusUnauthorized, response.Response{
					Code:    http.StatusUnauthorized,
					Message: "Token has expired",
					Data:    nil,
				})
				c.Abort()
				return
			}

			// 将解析后的Claims信息存储到gin的Context中，方便后续业务逻辑使用
			c.Set("username", claims.Username)
			c.Next()
		} else {
			logger.Info("Invalid token in request")
			c.JSON(http.StatusUnauthorized, response.Response{
				Code:    http.StatusUnauthorized,
				Message: "Invalid token",
			})
			c.Abort()
			return
		}
	}
}
